package com.lez.flowpractice2.fragment

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.lez.flowpractice2.databinding.FragmentArticleBinding
import com.lez.flowpractice2.model.Article
import com.lez.flowpractice2.viewmodel.ArticleViewModel
import com.lez.flowpractice2.viewmodel.UserViewModel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collect

class ArticleFragment : Fragment() {


    private val mBinding: FragmentArticleBinding by lazy {
        FragmentArticleBinding.inflate(layoutInflater)
    }

    //拿到ViewModel
    private val articleViewModel by viewModels<ArticleViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    //EditText输入转换为Flow
    private fun TextView.textWatcherFlow(): Flow<String> = callbackFlow {
        val textWatcher = object: TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                offer(s.toString())   //输入值 装到Flow中
            }
        }
        addTextChangedListener(textWatcher)
        //移除TextWatcher监听
        awaitClose { removeTextChangedListener(textWatcher) }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

           lifecycleScope.launchWhenCreated {
               mBinding.editText.textWatcherFlow().collect {
                   if(articleViewModel !=null){
                       articleViewModel.searchArticles(it)
                   }
               }
           }
           //LiveData监听
           articleViewModel.articles.observe(viewLifecycleOwner,{articles ->
               mBinding.showText.text = articles.toString()
           })

        }
//        mBinding.editText.addTextChangedListener(object: TextWatcher{
//            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
//            }
//            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
//            }
//            override fun afterTextChanged(s: Editable?) {
//                RetrofitClient.articleApi.searchArticles(s.toString().trim())
//            }
//        })
}